/**
 * @swagger
 * /api/high-goods/quantity-analysis:
 *   get:
 *     tags:
 *       - 高价值品统计
 *     summary: 获取高价值品数量分析数据
 *     description: 分析高价值品的数量分布、统计和趋势，支持时间筛选
 *     parameters:
 *       - in: query
 *         name: startTime
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始时间 (YYYY-MM-DD)
 *         example: "2023-01-01"
 *       - in: query
 *         name: endTime
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束时间 (YYYY-MM-DD)
 *         example: "2023-12-31"
 *     responses:
 *       200:
 *         description: 成功获取数量分析数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                   description: 响应状态码
 *                 message:
 *                   type: string
 *                   example: "数量分析获取成功"
 *                   description: 响应消息
 *                 data:
 *                   type: object
 *                   properties:
 *                     basicStats:
 *                       type: object
 *                       properties:
 *                         totalQuantity:
 *                           type: number
 *                           description: 总数量
 *                         avgQuantity:
 *                           type: string
 *                           description: 平均数量
 *                         maxQuantity:
 *                           type: number
 *                           description: 最大数量
 *                         minQuantity:
 *                           type: number
 *                           description: 最小数量
 *                         recordCount:
 *                           type: number
 *                           description: 记录数
 *                         totalAmount:
 *                           type: number
 *                           description: 总金额
 *                     quantityDistribution:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           quantityRange:
 *                             type: string
 *                             description: 数量范围
 *                           recordCount:
 *                             type: number
 *                             description: 记录数
 *                           percentage:
 *                             type: string
 *                             description: 占比
 *                     timeAnalysis:
 *                       type: object
 *                       properties:
 *                         totalTimePoints:
 *                           type: number
 *                           description: 总时间点数
 *                         timeRange:
 *                           type: object
 *                           properties:
 *                             earliest:
 *                               type: string
 *                               description: 最早时间
 *                             latest:
 *                               type: string
 *                               description: 最晚时间
 *                         data:
 *                           type: array
 *                           items:
 *                             type: object
 *                             properties:
 *                               range:
 *                                 type: string
 *                                 description: 数量范围
 *                               count:
 *                                 type: integer
 *                                 description: 记录数
 *                               percentage:
 *                                 type: number
 *                                 description: 占比
 *                     trends:
 *                       type: object
 *                       properties:
 *                         description:
 *                           type: string
 *                           example: "数量趋势分析"
 *                         data:
 *                           type: array
 *                           items:
 *                             type: object
 *                             properties:
 *                               period:
 *                                 type: string
 *                                 description: 时间周期
 *                               totalQuantity:
 *                                 type: integer
 *                                 description: 总数量
 *                               avgQuantity:
 *                                 type: number
 *                                 description: 平均数量
 *       500:
 *         description: 服务器内部错误
 */
import { withCors } from '../../../lib/cors';
const { success, error: createError, handleResponse } = require('../../../lib/response');
const { query } = require('../../../lib/db');

/**
 * 处理高价值品数量分析请求
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function handler(req, res) {

  try {
    // 获取时间筛选参数
    const { startTime, endTime } = req.query;
    
    // 构建时间筛选条件
    let timeCondition = '';
    if (startTime || endTime) {
      const conditions = [];
      if (startTime) conditions.push(`TJSJ >= '${startTime}'`);
      if (endTime) conditions.push(`TJSJ <= '${endTime}'`);
      timeCondition = ` AND ${conditions.join(' AND ')}`;
    }
    
    // 时间基础统计
    const timeBasicQuery = `
      SELECT 
        COUNT(DISTINCT TJSJ) as totalTimePoints,
        MIN(TJSJ) as earliestTime,
        MAX(TJSJ) as latestTime,
        COUNT(*) as totalRecords,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE TJSJ IS NOT NULL AND TJSJ != ''${timeCondition}
    `;

    const timeBasicResult = await query(timeBasicQuery);
    const timeBasic = timeBasicResult[0];

    // 年度统计
    const yearlyQuery = `
      SELECT 
        YEAR(TJSJ) as year,
        COUNT(*) as recordCount,
        COUNT(DISTINCT DWMC) as unitCount,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount,
        AVG(COALESCE(GJZSL, 0)) as avgQuantity,
        AVG(COALESCE(GJZJE, 0)) as avgAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE TJSJ IS NOT NULL AND TJSJ != ''${timeCondition}
      GROUP BY YEAR(TJSJ)
      ORDER BY year DESC
    `;

    const yearlyResult = await query(yearlyQuery);

    // 数量分布统计
    const quantityDistributionQuery = `
      SELECT 
        CASE 
          WHEN COALESCE(GJZSL, 0) = 0 THEN '0个'
          WHEN GJZSL <= 5 THEN '1-5个'
          WHEN GJZSL <= 10 THEN '6-10个'
          WHEN GJZSL <= 20 THEN '11-20个'
          WHEN GJZSL <= 50 THEN '21-50个'
          ELSE '50个以上'
        END as quantityRange,
        COUNT(*) as recordCount
      FROM wd_zcgk_gjzzcdwfb
      WHERE 1=1${timeCondition}
      GROUP BY 
        CASE 
          WHEN COALESCE(GJZSL, 0) = 0 THEN '0个'
          WHEN GJZSL <= 5 THEN '1-5个'
          WHEN GJZSL <= 10 THEN '6-10个'
          WHEN GJZSL <= 20 THEN '11-20个'
          WHEN GJZSL <= 50 THEN '21-50个'
          ELSE '50个以上'
        END
      ORDER BY 
        CASE 
          WHEN quantityRange = '0个' THEN 0
          WHEN quantityRange = '1-5个' THEN 1
          WHEN quantityRange = '6-10个' THEN 2
          WHEN quantityRange = '11-20个' THEN 3
          WHEN quantityRange = '21-50个' THEN 4
          ELSE 5
        END
    `;

    const quantityDistributionResult = await query(quantityDistributionQuery);

    // 月度统计
    const monthlyQuery = `
      SELECT 
        DATE_FORMAT(TJSJ, '%Y-%m') as month,
        COUNT(*) as recordCount,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE TJSJ IS NOT NULL AND TJSJ != ''${timeCondition}
      GROUP BY DATE_FORMAT(TJSJ, '%Y-%m')
      ORDER BY month DESC
      LIMIT 12
    `;

    const monthlyResult = await query(monthlyQuery);

    const responseData = {
      basicStats: {
        totalQuantity: parseInt(timeBasic.totalQuantity),
        avgQuantity: parseFloat(timeBasic.totalQuantity / timeBasic.totalRecords || 0).toFixed(2),
        maxQuantity: Math.max(...quantityDistributionResult.map(item => {
          const range = item.quantityRange;
          if (range === '50个以上') return 50;
          if (range === '0个') return 0;
          const match = range.match(/(\d+)-(\d+)个/);
          return match ? parseInt(match[2]) : 0;
        })),
        minQuantity: 0,
        recordCount: parseInt(timeBasic.totalRecords),
        totalAmount: parseFloat(timeBasic.totalAmount)
      },
      quantityDistribution: quantityDistributionResult.map(item => ({
        quantityRange: item.quantityRange,
        recordCount: parseInt(item.recordCount),
        percentage: ((parseInt(item.recordCount) / parseInt(timeBasic.totalRecords)) * 100).toFixed(2)
      })),
      timeAnalysis: {
        totalTimePoints: parseInt(timeBasic.totalTimePoints),
        timeRange: {
          earliest: timeBasic.earliestTime,
          latest: timeBasic.latestTime
        }
      }
    };

    return handleResponse(res, success(responseData, "数量分析获取成功"));
    
  } catch (err) {
    console.error('High goods quantity analysis error:', err);
    return handleResponse(res, createError("获取数量分析失败", 500));
  }
}

export default withCors(handler, ['GET']);